package com.example.everying.service.statistics.impl;/*
 * 项目名称: everything
 * 文件名: UserRetentionStatServiceImpl
 * 作者: 张泽阳
 * 日期: 2025/7/12
 * 描述:
 */

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.everying.mapper.statistics.UserRetentionStatMapper;
import com.example.everying.model.entity.statistics.UserRetentionStat;
import com.example.everying.service.statistics.UserRetentionStatService;
import com.example.everying.service.statistics.UserSessionService;
import com.example.everying.service.user.UserService;
import com.example.everying.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Service
public class UserRetentionStatServiceImpl extends ServiceImpl<UserRetentionStatMapper, UserRetentionStat> implements UserRetentionStatService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserSessionService userSessionService;
    @Override
    public Result<?> addRetentionStat() {

        LocalDateTime startTime = LocalDateTime.now()
                .truncatedTo(ChronoUnit.DAYS)
                .minusDays(2);
        LocalDateTime endTime  = startTime.plusDays(1);
        int signUserCount = userService.getSignCount(startTime,endTime);
        int activeUserCount = userSessionService.getStatCohortCount(LocalDate.now().minusDays(1),LocalDate.now().minusDays(2));
        double rr1 = 0;
        double rr7 = 0;
        if (activeUserCount != 0){
            rr1 = (double) activeUserCount /signUserCount;
        }
        startTime = LocalDateTime.now()
                .truncatedTo(ChronoUnit.DAYS)
                .minusDays(8);

        endTime  = startTime.plusDays(1);
        signUserCount = userService.getSignCount(startTime,endTime);
        activeUserCount = userSessionService.getStatCohortCount(LocalDate.now().minusDays(1),LocalDate.now().minusDays(8));
        if (activeUserCount != 0){
            rr7 = (double) activeUserCount /signUserCount;
        }
        UserRetentionStat userRetentionStat = new UserRetentionStat();
        userRetentionStat.setStatDate(LocalDate.now().minusDays(1));
        userRetentionStat.setRr1(BigDecimal.valueOf(rr1));
        userRetentionStat.setRr7(BigDecimal.valueOf(rr7));
        userRetentionStat.setCreateTime(LocalDateTime.now());
        userRetentionStat.setUpdateTime(LocalDateTime.now());
        save(userRetentionStat);
        return null;
    }
}
